import { Router } from 'express';
import { UrlEntity } from '../../framework/baseUrl';
import {type LoginTypeEntity} from 'spen-common/src/interface/RequestOperation'
import { getLoginCode, login } from '../server/LoginService';
import { Result } from 'spen-common/src/Result';
const app = Router()
app.post("/login", async (req, res)=>{
    let body: LoginTypeEntity = req.body;
    let loginType = body.type;
    if(['code', 'phone', 'email'].indexOf(loginType) == -1 && loginType != req.session.authenCode.type){
        res.send( <Result>{
                code: 'error',
                msg: '登陆类型错误'
            }
        )
    }
    if(loginType == req.session.authenCode.type){
        if(body.body.account != req.session.authenCode.code){
            res.send( <Result>{
                code: 'error',
                msg: '未获取认证码'
            })
        }
    }
    let user = await login(body);
    if(user == null){
        res.send( <Result>{
            code: 'error',
            msg: '登录失败!'
        })
    }
    req.session.user = user;
    res.send('login');
})

app.get("/code", async(req, res)=>{
    let body: LoginTypeEntity = req.body;
    let code = await getLoginCode(body);
    if(code != null && (body.type =='email-code' || body.type =='phone-code') ){
        req.session.authenCode = {
            type: body.type ,
            code: code
        }
        res.send(<Result<any>>{
            code: 'ok',
            data: req.session.authenCode
        })
    }
})

export default <UrlEntity>{
    application: app,
    type: 'router'
}
